package com.rainbow.support.influxdb.config;

import com.rainbow.support.influxdb.properties.InfluxdbProperties;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;



/**
 * influxdb配置
 * @author 付为地
 * https://github.com/influxdata/influxdb-java
 */
@Configuration
@EnableConfigurationProperties(InfluxdbProperties.class)
@ConditionalOnProperty(prefix= InfluxdbProperties.EXTRA_INFLUXDB_PREFIX,name = "enable", havingValue = "true")
@Slf4j
public class InfluxDbConfig {

    @Resource
    private InfluxdbProperties influxdbProperties;

    /**
     * 异步插入：
     * enableBatch这里第一个是point的个数，第二个是时间，单位毫秒
     * point的个数和时间是联合使用的，如果满100条或者2000毫秒
     * 满足任何一个条件就会发送一次写的请求。
     */
    @Bean
    @ConditionalOnMissingBean(InfluxDB.class)
    public InfluxDB influxDb() {
        InfluxDB influxDb = InfluxDBFactory.connect(influxdbProperties.getUrl(), influxdbProperties.getUsername(), influxdbProperties.getPassword());
        try {
            if (!influxDb.databaseExists(influxdbProperties.getDatabase())) {
                influxDb.createDatabase(influxdbProperties.getDatabase());
            }
            influxDb.setDatabase(influxdbProperties.getDatabase()).enableBatch(influxdbProperties.getActions(), influxdbProperties.getDuration(), TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("error with influxdb config", e);
        } finally {
            influxDb.setRetentionPolicy("autogen");
        }
        influxDb.setLogLevel(InfluxDB.LogLevel.BASIC);
        return influxDb;
    }
}
